/*
 * spring-security-oidc - spring-security-oidc
 * Copyright © 2022-Present Jinan Yuanchuang Network Technology Co., Ltd. (support@topiam.cn)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.topiam.employee.sample.oidc;

import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import static org.springframework.security.config.Customizer.withDefaults;

/**
 * OAuth2SecurityConfiguration
 *
 * @author SanLi
 * Created by qinggang.zuo@gmail.com / 2689170096@qq.com on  2022/10/24 12:57
 */
@Configuration
public class OidcSecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http,
                                                   ClientRegistrationRepository clientRegistrationRepository) throws Exception {
        // @formatter:off
        //静态资源
        http.authorizeHttpRequests(registry -> registry
            .requestMatchers(new OrRequestMatcher(
                new AntPathRequestMatcher("/index", HttpMethod.GET.toString()),
                new AntPathRequestMatcher("/login", HttpMethod.GET.toString())),
                new AntPathRequestMatcher("/css/**", HttpMethod.GET.toString()),
                new AntPathRequestMatcher("/js/**", HttpMethod.GET.toString()),
                new AntPathRequestMatcher("/images/**", HttpMethod.GET.toString()),
                new AntPathRequestMatcher("/webjars/**", HttpMethod.GET.toString()),
                new AntPathRequestMatcher("/favicon.ico", HttpMethod.GET.toString()),
                new AntPathRequestMatcher("/actuator/health", HttpMethod.GET.toString())
            )
            .permitAll().anyRequest().authenticated());
        http.logout(logoutConfigurer -> {
                    logoutConfigurer.logoutUrl("/logout");
                    logoutConfigurer.invalidateHttpSession(true);
                    logoutConfigurer.clearAuthentication(true);
                    OidcClientInitiatedLogoutSuccessHandler oidcClientInitiatedLogoutSuccessHandler = new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);
                    oidcClientInitiatedLogoutSuccessHandler.setPostLogoutRedirectUri("http://127.0.0.1:8080/login?logout");
                    logoutConfigurer.logoutSuccessHandler(oidcClientInitiatedLogoutSuccessHandler);
                })
                .oauth2Login(config -> {
                    config.loginPage("/login");
                    config.defaultSuccessUrl("/index",true);
                })
                .oauth2Client(withDefaults())
                //csrf
                .csrf(AbstractHttpConfigurer::disable);
        return http.build();
        // @formatter:on
    }

    private final WebEndpointProperties webEndpointProperties;

    public OidcSecurityConfiguration(WebEndpointProperties webEndpointProperties) {
        this.webEndpointProperties = webEndpointProperties;
    }
}
